<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Role extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'role';

    /**
     * 关联角色权限
     *
     * @return void
     */
    public function conPermission()
    {
        //return $this->hasManyThrough(Permission::class, RolePermissionModel::class, 'permission_id', 'role_id');
        return $this->belongsToMany('App\Models\Permission', 'role_permission', 'role_id', 'permission_id');
    }



    /**
     * 获取角色列表
     * @param keywords 筛选条件
     * @param limit 限制条件  为null则不分页
     */
    public function getRoleList($keywords = null, $limit = null)
    {

        //查看所有下级管理员id
        $manageModelObj = new Manage();
        $manage_id_all = $manageModelObj->getManageIdAll(request()->manage_id);
        //获取管理员的角色
        $manageRoleModelObj = new ManageRole();
        $role_id_all = $manageRoleModelObj->getManageRole(request()->manage_id);
        $role_id_all = array_column($role_id_all, 'id');

        // DB::enableQueryLog();
        $res = $this->select('id', 'role_name', 'create_time', 'change_time')->where(function ($query) use ($keywords) {
            if (!empty($keywords)) {
                $query->where('role_name', 'like', "%$keywords%");
            }
        })
            ->with(['conPermission' => function ($query) {
                $query->select('permission.id', 'permission.permission_name')->where('permission.is_del', 1);
            }])
            ->where('is_del', 1)
            ->where(function ($query) use ($manage_id_all, $role_id_all) {
                if ($manage_id_all) {
                    $query->orWhereIn('manage_id', $manage_id_all);
                }
                if ($role_id_all) {
                    $query->orWhereIn('id', $role_id_all);
                }
            })
            // ->where('manage_id' , $manage_id_all)
            ->orderByDesc('id');

        if ($limit) {
            $result = $res->paginate($limit)->toArray();
        } else {
            $result = $res->get()->toArray();
        }

        //   dump(DB::getQueryLog());

        return $result;
    }


    /**
     *  角色添加
     * @param $data 添加的数据
     */
    public function add($data, $field = [])
    {
        $this->role_name = $data->role_name;
        $this->manage_id = $data->manage_id;
        $this->is_del = 1;

        $this->save();

        $rolePermissionModelObj = new RolePermission();
        $rolePermissionModelObj->rolePermissionChange($this->id, $data->permission_ids, 'add');
    }

    /**
     * 修改角色
     * @param $data 添加的数据
     */
    public function change($data, $field = [], $findWhere = [])
    {
        $res = $this->where('is_del', 1)->find($data['id']);
        if (!$res) {
            return false;
        }
        $res->role_name = $data->role_name;

        $res->save();

        $rolePermissionModelObj = new RolePermission();
        $rolePermissionModelObj->rolePermissionChange($data->id, $data->permission_ids, 'change');
    }


    /**
     * 判断角色是否已经存在
     * @param role_name 角色名称
     * @param id 角色id   可选，主要是用于修改
     */
    public function roleIsExists($role_name, $id = null)
    {
        $res = $this->where('role_name', $role_name)->where(function ($query) use ($id) {
            if (!empty($id)) {
                $query->where('id', '<>', $id);
            }
        })->where('is_del', 1)->first();
        return $res;
    }
}
